package com.group.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.group.dao.TbUserRoleMapper;
import com.group.pojo.Common;
import com.group.pojo.TbUser;
import com.group.pojo.TbUserRole;
import com.group.pojo.TbUserRoleExample;
import com.group.pojo.TbUserRoleExample.Criteria;
import com.group.service.CommonService;
import com.group.service.UserRoleService;
import com.group.util.CommonUtil;

@Service
public class UserRoleServiceImpl implements UserRoleService{

	@Autowired
	private TbUserRoleMapper userRoleMapper;
	@Autowired
	private CommonService commonService;
	
	@Override
	public Map<String, String> save(HttpServletRequest request, TbUserRole userRole) {
		
		Map<String, String> map = CommonUtil.getReturnMap("success", "true");
		//设置创建人、状态
		TbUser user = (TbUser) request.getSession().getAttribute("USER_SESSION");
		userRole.setCreateUserId(user.getId());
		userRole.setUserRoleStatus("1");
		
		//保存用户角色信息时，先要删掉已经存在的用户角色
		TbUserRoleExample oldRoles = new TbUserRoleExample();
		oldRoles.createCriteria().andUserIdEqualTo(userRole.getUserId()).andUserRoleStatusEqualTo("1");
		int deletes = userRoleMapper.deleteByExample(oldRoles);
		System.out.println("在更新【"+user.getUserName()+"】角色之前，删掉了原来的【"+deletes+"】个角色。");
		
		String[] roleIds = userRole.getRoleIds();
		for (String roleId : roleIds) {
			//设置创建时间
			userRole.setCreateTime(new Date());
			//设置id
			String nextId = commonService.getTbCurrentDateNextId(new Common("tb_user_role", CommonUtil.getCurrentDate("yyyyMMdd")));
			userRole.setId(nextId);
			//设置角色id
			userRole.setRoleId(roleId);
			int insert = userRoleMapper.insert(userRole);
			if (insert != 1) {
				map.put("success", "false");
				return map;
			}
		}
		return map;
	}

	@Override
	public List<TbUserRole> getUserRoles(TbUserRole userRole) {
		TbUserRoleExample example = new TbUserRoleExample();
		//status限制
		Criteria criteria = example.createCriteria();
		criteria.andUserRoleStatusEqualTo("1");

		String userId = userRole.getUserId();
		if (userId != null && !"".equals(userId)) {
			criteria.andUserIdEqualTo(userId);
		}
		
		List<TbUserRole> userRoles = userRoleMapper.selectByExample(example);
		
		return userRoles;
	}

}
